package cn.sangkf.litemall.search.service.impl;

import cn.sangkf.litemall.common.to.SkuEsModel;
import cn.sangkf.litemall.search.config.ElasticSearchConfig;
import cn.sangkf.litemall.search.constant.EsConstant;
import cn.sangkf.litemall.search.service.ProductSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : sangkf
 * @package : cn.sangkf.litemall.search.service.impl.ProductSaveServiceImpl
 * @date : 2021/1/10 下午3:29 星期日
 * @description : TODO
 * @version: 1.0
 * <p>Copyright: Copyright (c) 2020</p>
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //TODO 如果批量错误
        boolean hasFailures = bulk.hasFailures();
        List<String> list = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
        log.info("商品上架完成, {}, 返回数据: {}", list, bulk.toString());
        return hasFailures;
    }
}
